package com.yao.mall.interceptor;

import cn.hutool.json.JSONUtil;
import com.yao.mall.common.UserHolder;
import com.yao.mall.model.vo.UserVO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.concurrent.TimeUnit;

import static com.yao.mall.constant.UserConstant.LOGIN_USER_KEY;


/**
 * @author jiahua.yao
 * @version 1.0
 * @description 刷新登录时间
 * @date 2024/3/1 14:15
 */
@Slf4j
public class RefreshLoginInterceptor implements HandlerInterceptor {
    private final StringRedisTemplate stringRedisTemplate;
    public RefreshLoginInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头中的token
        String token = request.getHeader("authorization");
        if(StringUtils.isEmpty(token)){
            //不做拦截只做刷新时间的操作，故而直接放行
            return true;
        }
        //从Redis中获取用户,并重新转为user对象
        String json = stringRedisTemplate.opsForValue().get(LOGIN_USER_KEY + token);
        if(json == null){
            return true;
        }
        UserVO userVO = JSONUtil.toBean(json, UserVO.class);
        UserHolder.saveUser(userVO);
        //重新刷新token的有效时间
        stringRedisTemplate.expire(LOGIN_USER_KEY+token,30, TimeUnit.MINUTES);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
